import { Hct, SchemeTonalSpot, hexFromArgb, MaterialDynamicColors } from "@material/material-color-utilities";

function detectSystemAccent() {
  const detectElement = document.createElement("div");
  detectElement.style.background = "AccentColor";
  document.body.appendChild(detectElement);
  const color = window.getComputedStyle(detectElement).background;
  detectElement.remove();
  const matched = color.match("rgb\\(([0-9]+) *, *([0-9]+) *, *([0-9]+)\\)");
  if (matched) {
    const r = parseInt(matched[1]);
    const g = parseInt(matched[2]);
    const b = parseInt(matched[3]);
    const color = ((0xFF << 24) | (r * 65536) | (g * 255) | b) >>> 0;
    return color;
  }
  return -1;
}

function enableDynamicColor() {
  applyDynamicColor();
  window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
    applyDynamicColor();
  });
}

function applyDynamicColor() {
  const sourceColor = detectSystemAccent();

  if (sourceColor > 0) {
    const source = Hct.fromInt(sourceColor);
    const systemDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
    const scheme = new SchemeTonalSpot(source, systemDark, 0);
    const target = document.getElementById("app");

    for (const [key, value] of Object.entries(MaterialDynamicColors)) {
      if (typeof (value) != "object") {
        continue;
      }
      const token = key.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
      const color = hexFromArgb(value.getArgb(scheme));
      target.style.setProperty(`--md-sys-color-${token}`, color);
    }
  }
}

export { enableDynamicColor };